package com.r2coding.security.mobile;

import com.r2coding.security.CustomMobileUserDetailService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.Objects;

/**
 * @author: 98k灬
 * @since: 2022/11/04
 * @email: 98k_style@sina.com
 * @公众号: 爪哇Guy灬
 **/
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 认证处理
     * 通过手机号码查询用户信息
     *
     * @param authentication the authentication request object.
     * @return Authentication
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken token = (MobileAuthenticationToken) authentication;
        String mobile = (String)token.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        if (Objects.isNull(userDetails)) {
            throw new AuthenticationServiceException("该手机号码未注册");
        }
        MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile, userDetails.getAuthorities());
        mobileAuthenticationToken.setDetails(token.getDetails());
        return mobileAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
